<template>
    <div class="configure-container">
        <div class="configure-header">
            <h3>{{ isHeaderMode ? '表头' : '组件配置' }}</h3>
        </div>

        <div class="configure-content">
            <!-- Header 配置表单 -->
            <el-form v-if="isHeaderMode" class="config-form" label-position="top" :model="headerConfig">
                <div class="config-section">
                    <h4>表头配置</h4>

                    <el-form-item>
                        <template #label>
                            <div class="header-title-label">
                                <span>表头名称</span>
                                <el-checkbox v-model="headerConfig.hideTitle"
                                    style="margin-left: 16px;">隐藏表头名称</el-checkbox>
                            </div>
                        </template>
                        <el-input v-model="headerConfig.title" placeholder="请输入表头名称" :maxlength="14" show-word-limit />
                    </el-form-item>

                    <el-form-item label="描述内容">
                        <el-input v-model="headerConfig.description" type="textarea" placeholder="建议在此输入机构的介绍内容或表单的填写引导"
                            :maxlength="45" show-word-limit :rows="3" />
                    </el-form-item>

                    <el-form-item label="背景图">
                        <div class="avatar-uploader" @click="showHeaderImageDialog = true">
                            <el-image v-if="headerConfig.backgroundImage" :src="headerConfig.backgroundImage"
                                class="avatar" fit="contain"></el-image>
                            <div v-if="headerConfig.backgroundImage" class="mask">替换</div>
                            <el-icon v-if="headerConfig.backgroundImage" class="del-image" :size="20"
                                @click.stop="handleDelHeaderImg">
                                <CircleCloseFilled />
                            </el-icon>
                            <i v-else class="el-icon-plus avatar-uploader-icon">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </i>
                        </div>
                        <!-- <div class="image-tip">
                            建议尺寸: 750*320px, jpg、jpeg、png格式图片,大小不超过5M
                        </div> -->
                    </el-form-item>
                </div>

                <div class="config-actions">
                    <el-button type="primary" @click="saveHeaderConfig" class="btn-save">保存</el-button>
                    <el-button @click="resetHeaderConfig" class="btn-reset">重置</el-button>
                </div>
            </el-form>

            <!-- 组件配置表单 -->
            <el-form v-else class="config-form" label-position="top" :model="componentConfig">
                <div class="config-section">
                    <h4>基础设置</h4>

                    <el-form-item label="标题" v-if="!hasRichText && !hasImage">
                        <el-input v-model="componentConfig.label" placeholder="标题不能为空" />
                    </el-form-item>

                    <el-form-item label="标题描述" v-if="!hasRichText && !hasImage">
                        <el-input v-model="componentConfig.remark" placeholder="请输入标题描述" />
                    </el-form-item>

                    <el-form-item label="默认提示文字" v-if="hasDefaultText">
                        <el-input v-model="componentConfig.defaultText" />
                    </el-form-item>

                    <el-form-item label="是否必填" v-if="!hasRichText && !hasImage">
                        <el-checkbox v-model="componentConfig.required">必填项</el-checkbox>
                    </el-form-item>

                    <el-form-item label="接受的日期格式" v-if="hasDateFormat">
                        <el-radio-group v-model="componentConfig.date">
                            <el-radio value="1">年-月-日</el-radio>
                            <el-radio value="2">年-月</el-radio>
                            <el-radio value="3">日期范围</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-checkbox v-if="hasUploadNum"
                        v-model="componentConfig.upoladNum">只允许上传一张图片（默认可上传9张图片）</el-checkbox>

                    <el-form-item v-if="hasRichText">
                        <ArtWangEditor v-model="componentConfig.richText" />
                    </el-form-item>

                    <el-form-item label="图片" prop="name" v-if="hasImage">
                        <div class="avatar-uploader" @click=" showImageChooseDialog = true">
                            <el-image v-if="componentConfig.image" :src="componentConfig.image" class="avatar"
                                fit="contain"></el-image>
                            <div v-if="componentConfig.image" class="mask">替换</div>
                            <el-icon v-if="componentConfig.image" class="del-image" :size="20"
                                @click.stop="handleDelImg">
                                <CircleCloseFilled />
                            </el-icon>
                            <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                                    <Plus />
                                </el-icon></i>
                        </div>
                    </el-form-item>

                    <el-form-item v-if="hasImage">
                        <el-checkbox v-model="componentConfig.isJump">点击图片跳转页面</el-checkbox>
                        <el-input v-if="componentConfig.isJump" v-model="componentConfig.url" placeholder="请输入内容" />
                    </el-form-item>

                    <el-form-item label="选择格式" v-if="hasAddress">
                        <el-radio-group v-model="componentConfig.addressType">
                            <el-radio value="1">省</el-radio>
                            <el-radio value="2">省-市</el-radio>
                            <el-radio value="3">省-市-区/县</el-radio>
                            <el-radio value="4">省-市-区/县</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>

                <div v-if="hasOptions" class="config-section">
                    <h4>选项设置</h4>
                    <div class="options-list">
                        <div v-for="(option, index) in componentConfig.options" :key="index" class="option-item">
                            <el-input v-model="option.label" placeholder="选项文本" class="option-input" />
                            <el-button type="danger" size="small" @click="removeOption(index)" plain>删除</el-button>
                        </div>
                        <el-button type="primary" link icon="el-icon-plus" @click="addOption" class="btn-add-option"
                            v-if="!hasGender">+
                            添加选项
                        </el-button>
                    </div>
                </div>

                <div class="config-actions">
                    <el-button type="primary" @click="saveConfig" class="btn-save">保存</el-button>
                    <el-button @click="resetConfig" class="btn-reset">重置</el-button>
                </div>
            </el-form>
        </div>
    </div>
    <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
        :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
        :operationType="false"></image-selected-dialog>
    <image-selected-dialog v-if="showHeaderImageDialog" :single-type="selectImageSingle"
        :show-image-choose-dialog="showHeaderImageDialog" @close-dialog="handleCloseHeaderImageDialog"
        :operationType="false"></image-selected-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'

const selectedComponent = ref<any>(null)
const isHeaderMode = ref(false)
const componentConfig = ref<any>({
    label: '',
    placeholder: '',
    required: true,
    options: [],
    remark: '',
    defaultText: '',
    date: '1',
    upoladNum: false,
    richText: '',
    image: '',
    isJump: false,
    url: '',
    addressType: '1' // 保证有初始值
})

// Header 配置数据
const headerConfig = ref({
    title: '测试',
    description: '',
    backgroundImage: '',
    hideTitle: false
})

const showImageChooseDialog = ref(false)
const showHeaderImageDialog = ref(false)
const selectImageSingle = ref(true)

const handleDelImg = () => {
    componentConfig.value.image = ''
}

const handleDelHeaderImg = () => {
    headerConfig.value.backgroundImage = ''
}

const handleCloseImageDialog = (value: any) => {
    if (value && value.fileUrl) {
        componentConfig.value.image = value.fileUrl
    }
    showImageChooseDialog.value = false
}

const handleCloseHeaderImageDialog = (value: any) => {
    if (value && value.fileUrl) {
        headerConfig.value.backgroundImage = value.fileUrl
    }
    showHeaderImageDialog.value = false
}

// 判断是否有选项配置 单选、多选
const hasOptions = computed(() => {
    return selectedComponent.value && ['radio', 'checkbox', 'gender'].includes(selectedComponent.value.type)
})

// 判断是否有默认提示文字 文本框使用
const hasDefaultText = computed(() => {
    return selectedComponent.value && ['textarea', 'name', 'age', 'company', 'phone', 'idcard'].includes(selectedComponent.value.type)
})
// 判断是否有日期格式 日期格式使用
const hasDateFormat = computed(() => {
    return selectedComponent.value && ['date'].includes(selectedComponent.value.type)
})
// 判断图片上传张数 上传图片使用
const hasUploadNum = computed(() => {
    return selectedComponent.value && ['upload'].includes(selectedComponent.value.type)
})
// 判断是否有富文本 文本描述使用
const hasRichText = computed(() => {
    return selectedComponent.value && ['richText'].includes(selectedComponent.value.type)
})
// 判断是否有上传图片  图片使用
const hasImage = computed(() => {
    return selectedComponent.value && ['image'].includes(selectedComponent.value.type)
})
// 判断是否是性别选项  性别使用
const hasGender = computed(() => {
    return selectedComponent.value && ['gender'].includes(selectedComponent.value.type)
})
// 判断是否是地址 地址使用
const hasAddress = computed(() => {
    return selectedComponent.value && ['address'].includes(selectedComponent.value.type)
})

// 监听选中组件变化
watch(
    selectedComponent,
    (newComponent) => {
        if (newComponent) {
            const defaultTextMap: any = {
                name: '请输入姓名',
                age: '请输入年龄',
                company: '请输入公司',
                phone: '请输入手机号',
                idcard: '请输入身份证号'
            }
            newComponent.defaultText = defaultTextMap[newComponent.type] || '请输入内容'
            componentConfig.value = {
                label: newComponent.label || '',
                placeholder: newComponent.placeholder || '',
                required: newComponent.required || true,
                options: newComponent.options ? JSON.parse(JSON.stringify(newComponent.options)) : [],
                remark: newComponent.remark || '',
                defaultText: newComponent.defaultText || '',
                date: newComponent.date || '1',
                upoladNum: newComponent.upoladNum || false,
                richText: newComponent.richText || '',
                image: newComponent.image || '',
                isJump: newComponent.isJump || false,
                url: newComponent.url || '',
                addressType: newComponent.addressType || '1' // 保证地址类型有默认值
            }
            initializeOptions()
        }
    },
    { immediate: true }
)

// 监听配置变化，实时更新组件
watch(
    componentConfig,
    (newConfig) => {
        if (selectedComponent.value) {
            Object.assign(selectedComponent.value, newConfig)
        }
    },
    { deep: true }
)

// 添加选项
const addOption = () => {
    componentConfig.value.options.push({
        label: `选项${componentConfig.value.options.length + 1}`,
        value: `option_${componentConfig.value.options.length + 1}`
    })
}

// 初始化选项（如果没有选项的话）
const initializeOptions = () => {
    const type = selectedComponent.value.type
    if (
        selectedComponent.value &&
        hasOptions.value &&
        (!componentConfig.value.options || componentConfig.value.options.length === 0)
    ) {
        componentConfig.value.options = [
            { label: type === 'gender' ? '男' : '选项1', value: 'option1' },
            { label: type === 'gender' ? '女' : '选项2', value: 'option2' },
            { label: type === 'gender' ? '(保密)' : '选项3', value: 'option3' }
        ]
    }
}

// 删除选项
const removeOption = (index: number) => {
    if (componentConfig.value.options.length > 1) {
        componentConfig.value.options.splice(index, 1)
    } else {
        ElMessage.error('不能再删除了')
    }
}

// 保存配置
const saveConfig = () => {
    console.log(selectedComponent.value, "selectedComponent.value===");

    if (selectedComponent.value) {
        Object.assign(selectedComponent.value, componentConfig.value)
        console.log(componentConfig.value, "componentConfig.value===");

        ElMessage.success('配置已保存！')
    }
}

// 重置配置
const resetConfig = () => {
    if (selectedComponent.value) {
        componentConfig.value = {
            label: selectedComponent.value.label || '',
            placeholder: selectedComponent.value.placeholder || '',
            required: selectedComponent.value.required || true,
            options: selectedComponent.value.options ? JSON.parse(JSON.stringify(selectedComponent.value.options)) : [],
            remark: selectedComponent.value.remark || '',
            defaultText: selectedComponent.value.defaultText || '',
            date: selectedComponent.value.date || '1',
            upoladNum: selectedComponent.value.upoladNum || false,
            richText: selectedComponent.value.richText || '',
            image: selectedComponent.value.image || '',
            addressType: selectedComponent.value.addressType || '1'
        }
    }
}

// 保存 Header 配置
const saveHeaderConfig = () => {
    // 通过 emit 或 ref 通知父组件更新 header 配置
    // 这里假设有父组件传入的方法
    if (updateHeaderConfigCallback.value) {
        updateHeaderConfigCallback.value(headerConfig.value)
    }
    ElMessage.success('配置已保存！')
}

// 重置 Header 配置
const resetHeaderConfig = () => {
    // 重置为初始值
    headerConfig.value = {
        title: '测试',
        description: '',
        backgroundImage: '',
        hideTitle: false
    }
}

// 存储更新 header 配置的回调函数
const updateHeaderConfigCallback = ref<((config: any) => void) | null>(null)

// 监听 headerConfig 变化,实时更新预览
watch(
    headerConfig,
    (newConfig) => {
        if (isHeaderMode.value && updateHeaderConfigCallback.value) {
            updateHeaderConfigCallback.value(newConfig)
        }
    },
    { deep: true }
)

// 暴露方法给父组件调用
defineExpose({
    setSelectedComponent: (component: any) => {
        isHeaderMode.value = false
        selectedComponent.value = component
        if (component) {
            componentConfig.value = {
                label: component.label || '',
                placeholder: component.placeholder || '',
                required: component.required || true,
                options: component.options ? JSON.parse(JSON.stringify(component.options)) : [],
                remark: component.remark || '',
                defaultText: component.defaultText || '',
                date: component.date || '1',
                upoladNum: component.upoladNum || false,
                richText: component.richText || '',
                image: component.image || '',
                addressType: component.addressType || ''
            }
        }
    },
    setHeaderConfig: (config: any, updateCallback: (config: any) => void) => {
        isHeaderMode.value = true
        selectedComponent.value = null
        if (config) {
            headerConfig.value = { ...config }
        }
        updateHeaderConfigCallback.value = updateCallback
    }
})
</script>

<style lang="scss" scoped>
.configure-container {
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
}

.configure-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e8e8e8;
    background: #fafafa;

    h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
    }
}

.configure-content {
    height: calc(100% - 60px);
    padding: 20px;
    overflow-y: auto;
}

.config-form {
    display: flex;
    flex-direction: column;
    gap: 24px;
}

.config-section h4 {
    margin: 0 0 16px 0;
    font-size: 14px;
    font-weight: 600;
    color: #333;
    padding-bottom: 8px;
    border-bottom: 1px solid #e8e8e8;
}

.options-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.option-item {
    display: flex;
    gap: 8px;
    align-items: center;
}

.option-input {
    flex: 1;
}

.btn-add-option {
    margin-top: 8px;
    padding: 0;
}

.config-actions {
    display: flex;
    gap: 12px;
    padding-top: 16px;
    border-top: 1px solid #e8e8e8;
}

.btn-save,
.btn-reset {
    flex: 1;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;

    .mask {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 24px;
        background-color: rgba(0, 0, 0, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s ease;
        color: #fff;
        font-size: 12px;
    }

    .del-image {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        color: #8c939d;
    }

    &:hover .mask {
        opacity: 1;
    }

    &:hover .del-image {
        display: block;
    }
}

.avatar-uploader .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
    height: 100%;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.image-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
    line-height: 1.4;
}

.header-title-label {
    display: flex;
    align-items: center; 
    justify-content: space-between;
}

:deep(.el-form-item__label) {
    padding: 0;
}
</style>